package server.model.userModel;

import org.apache.commons.dbutils.handlers.BeanHandler;
import server.db.DBDriver;
import server.db.DBFactory;
import server.entity.Code;
import server.entity.User;
import server.model.factory.ModelFactory;
import server.util.InfoUtils.Info;
import server.util.InfoUtils.InfoEnum;
import server.util.InfoUtils.InfoUtil;
import server.util.MyUtils;

import java.util.ArrayList;
import java.util.List;

public class UserInfoModel {
    /**
     * 通过userId获取user信息
     *
     * @param userId
     * @return Info
     */
    public Info getUserInfoByUserId(Integer userId) {
        Info info = null;
        String sql = "select * from user where user_id = ? limit 1";
        User user = DBFactory.getDBDriver().query(sql, new BeanHandler<>(User.class, DBDriver.getProcess()), userId);
        if (user != null) {
            info = InfoUtil.getInfo(user);
        } else {
            info = InfoUtil.getInfo(InfoEnum.FAIL);
        }
        return info;
    }

    public Info getOtherUserInfo(Integer userId) {
        Info info = null;
        String sql = "select user_id,user_name,pic,store_id from user where user_id = ? limit 1";
        User user = DBFactory.getDBDriver().query(sql, new BeanHandler<>(User.class, DBDriver.getProcess()), userId);
        if (user != null) {
            info = InfoUtil.getInfo(user);
        } else {
            info = InfoUtil.getInfo(InfoEnum.FAIL);
        }
        return info;
    }

    /**
     * 设置user信息
     *
     * @param user 封装好的user对象
     * @return info
     */
    public Info setUserInfo(User user) {
        Info info = null;
        List<Object> params = new ArrayList<>();
        StringBuilder sql = new StringBuilder("update user set ");

        String userName = user.getUserName();
        if (MyUtils.NOTNULL(userName)) {
            //判断是否重名
            if (!ModelFactory.getUserModel().judgeUserName(userName)) {
                return InfoUtil.getInfo(1, "起名真难");
            }
            //设置code表中的user_name
            if (setNameOfCode(userName, user.getUserId()).getCode() != 0) {
                return InfoUtil.getInfo(InfoEnum.FAIL);
            }

            sql.append(" user_name = ?, ");
            params.add(userName);
        }

        String pic = user.getPic();
        if (MyUtils.NOTNULL(pic)) {
            sql.append(" pic = ?, ");
            params.add(pic);
        }

        Integer storeId = user.getStoreId();
        System.out.println(storeId);
        if (storeId != null) {
            sql.append(" store_id = ?, ");
            params.add(storeId);
        }

        String cart = user.getCart();
        if (MyUtils.NOTNULL(cart)) {
            sql.append(" cart = ?, ");
            params.add(cart);
        }

        String bought = user.getBought();
        if (MyUtils.NOTNULL(bought)) {
            sql.append(" bought = ?, ");
            params.add(bought);
        }

        String storeCollection = user.getStoreCollection();
        if (MyUtils.NOTNULL(storeCollection)) {
            sql.append(" store_collection = ?, ");
            params.add(storeCollection);
        }

        String goodCollection = user.getGoodCollection();
        if (MyUtils.NOTNULL(goodCollection)) {
            sql.append(" good_collection = ?, ");
            params.add(goodCollection);
        }

        //设置选择条件
        sql.append(" where user_id = ? limit 1 ");
        params.add(user.getUserId());

        //去除最后一个“,”
        String endSql = sql.deleteCharAt(sql.lastIndexOf(",")).toString();

        //操作数据库影响的行数
        int line = DBFactory.getDBDriver().update(endSql, params.toArray());

        if (line > 0) {
            info = InfoUtil.getInfo(InfoEnum.SUCCESS);
        } else {
            info = InfoUtil.getInfo(InfoEnum.FAIL);
        }
        return info;
    }

    /**
     * 设置用户金币
     *
     * @param code code 对象，gold属性-->增加或减少的金币，负代表减少
     * @return
     */
    public Info setGold(Code code) {
        Double money = code.getGold();
        if (!MyUtils.NOTNULL(money, code.getUserId())) {
            return InfoUtil.getInfo(InfoEnum.PARAMS_NULL);
        }
        //格式化money
        money = MyUtils.formatDouble(money);

        //判断是否有足够金额支付
        String getLastGoldSql = "select gold from code where user_id = " + code.getUserId();
        String lastGold = DBFactory.getDBDriver().queryOne(getLastGoldSql);
        //若为空，则请求失败
        if (lastGold == null) {
            return InfoUtil.getInfo(InfoEnum.FAIL);
        }
        Double last_gold = Double.parseDouble(lastGold);
        if (last_gold + money < 0) {
            return InfoUtil.getInfo(2, "余额不足");
        }

        //扣除或增加金币
        String sql = "update code set gold = gold + ? where user_id = ? limit 1";
        int line = DBFactory.getDBDriver().update(sql, money, code.getUserId());
        if (line > 0) {
            return InfoUtil.getInfo(InfoEnum.SUCCESS);
        } else {
            return InfoUtil.getInfo(InfoEnum.FAIL);
        }
    }

    //获取用户的金币数量
    public Info getGoldByUserId(Integer userId) {
        String sql = "select gold from code where user_id = &";
        String ans = DBFactory.getDBDriver().queryOne(sql, userId.toString());
        if (ans == null) {
            return InfoUtil.getInfo(InfoEnum.FAIL);
        }
        return InfoUtil.getInfo(Double.parseDouble(ans));
    }

    //设置code数据表的user_name
    public Info setNameOfCode(String userName, Integer userId) {
        String sql = "update code set user_name = ? where user_id = ?";

        if (DBFactory.getDBDriver().update(sql, userName, userId) <= 0) {
            return InfoUtil.getInfo(InfoEnum.FAIL);
        }
        return InfoUtil.getInfo(InfoEnum.SUCCESS);
    }

    public Info getUserIdByStoreId(Integer storeId) {
        String sql = "select user_id from user where store_id = ?";

        User user = DBFactory.getDBDriver().query(sql, new BeanHandler<>(User.class, DBDriver.getProcess()), storeId);

        if (user == null || user.getUserId() == null) {
            return InfoUtil.getInfo(InfoEnum.FAIL);
        }
        return InfoUtil.getInfo(user.getUserId());
    }
}
